<script setup lang="ts">
import { ref, onMounted, onUpdated, onUnmounted, onBeforeMount, onBeforeUpdate, onBeforeUnmount } from 'vue'

const count = ref(0)
const mountedTime = ref('')
const updateCount = ref(0)

// 组件挂载前
onBeforeMount(() => {
  console.log('1. onBeforeMount: 组件挂载前')
})

// 组件挂载后
onMounted(() => {
  console.log('2. onMounted: 组件挂载后')
  mountedTime.value = new Date().toLocaleTimeString()
  
  // 模拟异步数据加载
  setTimeout(() => {
    count.value = 100
  }, 1000)
})

// 组件更新前
onBeforeUpdate(() => {
  console.log('3. onBeforeUpdate: 组件更新前')
})

// 组件更新后
onUpdated(() => {
  console.log('4. onUpdated: 组件更新后')
  updateCount.value++
})

// 组件卸载前
onBeforeUnmount(() => {
  console.log('5. onBeforeUnmount: 组件卸载前')
})

// 组件卸载后
onUnmounted(() => {
  console.log('6. onUnmounted: 组件卸载后')
})

// 模拟异步数据加载
const loading = ref(true)
const data = ref<string[]>([])

onMounted(async () => {
  try {
    // 模拟 API 调用
    await new Promise(resolve => setTimeout(resolve, 1500))
    data.value = ['数据1', '数据2', '数据3']
  } finally {
    loading.value = false
  }
})

// 清理示例
const timer = ref<number>()

onMounted(() => {
  // 设置定时器
  timer.value = setInterval(() => {
    count.value++
  }, 1000)
})

onUnmounted(() => {
  // 清理定时器
  if (timer.value) {
    clearInterval(timer.value)
  }
})
</script>

<template>
  <div class="lifecycle-demo">
    <h2>生命周期钩子示例</h2>
    <p class="tip">请打开控制台查看生命周期钩子的执行顺序</p>

    <section>
      <h3>1. 基础状态</h3>
      <p>组件挂载时间: {{ mountedTime }}</p>
      <p>更新次数: {{ updateCount }}</p>
      <button @click="count++">更新组件 (count: {{ count }})</button>
    </section>

    <section>
      <h3>2. 异步数据加载</h3>
      <div v-if="loading">
        加载中...
      </div>
      <ul v-else>
        <li v-for="(item, index) in data" :key="index">
          {{ item }}
        </li>
      </ul>
    </section>

    <section>
      <h3>3. 自动计数器 (带清理)</h3>
      <p>计数: {{ count }}</p>
      <p class="tip">
        每秒自动增加，组件卸载时自动清理
      </p>
    </section>
  </div>
</template>

<style scoped>
.lifecycle-demo {
  padding: 20px;
}

section {
  margin: 20px 0;
  padding: 15px;
  border: 1px solid #ddd;
  border-radius: 8px;
}

.tip {
  color: #666;
  font-size: 0.9em;
  font-style: italic;
}

button {
  margin: 5px;
  padding: 5px 15px;
}

ul {
  list-style: none;
  padding: 0;
}

li {
  padding: 5px 0;
}
</style> 